package com.kung.qvs.entity.database;

import android.database.Cursor;
import android.text.TextUtils;

import com.kung.qvs.app.AppApplication;
import com.kung.qvs.entity.CustomerBean;
import com.kung.qvs.entity.DeviceBean;
import com.kung.qvs.entity.GarbageTypeBean;
import com.kung.qvs.entity.PrintDataBean;
import com.kung.qvs.entity.ProductBean;
import com.kung.qvs.entity.ProductInfoBean;
import com.kung.qvs.entity.PropInfoBean;
import com.kung.qvs.entity.PrintDataBean;
import com.kung.qvs.entity.SupplierBean;
import com.kung.qvs.entity.WorkerBean;
import com.kung.qvs.entity.greendao.CustomerBeanDao;
import com.kung.qvs.entity.greendao.DeviceBeanDao;
import com.kung.qvs.entity.greendao.GarbageTypeBeanDao;
import com.kung.qvs.entity.greendao.ProductBeanDao;
import com.kung.qvs.entity.greendao.ProductInfoBeanDao;
import com.kung.qvs.entity.greendao.PropInfoBeanDao;
import com.kung.qvs.entity.greendao.PrintDataBeanDao;
import com.kung.qvs.entity.greendao.SupplierBeanDao;
import com.kung.qvs.entity.greendao.WorkerBeanDao;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.utils.StringUtils;

public class SqlManager {

    /**
     * 保存我的设备
     *
     * @param bean
     * @return
     */
    public static long insertOrReplaceDeviceBean(DeviceBean bean) {
        DeviceBeanDao sqlDao = AppApplication.getDaoInstant().getDeviceBeanDao();
        DeviceBean deviceBean = queryDeviceBeanByType(bean.getFdeviceType(),bean.getFaccount());
        if(StringUtils.isTrimEmpty(bean.getFdevicesName()) && deviceBean != null
                && !StringUtils.isTrimEmpty(deviceBean.getFdevicesName())){
            bean.setFdevicesName(deviceBean.getFdevicesName());
        }
        return sqlDao.insertOrReplace(bean);
    }

    /**
     * 根据设备类型查询我的设备
     *
     * @param type
     * @return
     */
    public static DeviceBean queryDeviceBeanByType(String type, String faccount) {
        try {
            DeviceBeanDao sqlDao = AppApplication.getDaoInstant().getDeviceBeanDao();
            List<DeviceBean> list = sqlDao.queryBuilder().where(DeviceBeanDao.Properties.FdeviceType.eq(type),
                    DeviceBeanDao.Properties.Faccount.eq(faccount)).list();
            if (list != null && list.size() > 0) {
                return list.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除设备
     *
     * @param type
     */
    public static void deleteDeviceBeanByType(String type, String faccount) {
        DeviceBeanDao sqlDao = AppApplication.getDaoInstant().getDeviceBeanDao();
        sqlDao.queryBuilder().where(DeviceBeanDao.Properties.FdeviceType.eq(type),
                DeviceBeanDao.Properties.Faccount.eq(faccount)).buildDelete().executeDeleteWithoutDetachingEntities();
    }

    public static String queryDeviceBeanMacByType(String type, String faccount) {
        try {
            DeviceBeanDao sqlDao = AppApplication.getDaoInstant().getDeviceBeanDao();
            List<DeviceBean> list = sqlDao.queryBuilder().where(DeviceBeanDao.Properties.FdeviceType.eq(type),
                    DeviceBeanDao.Properties.Faccount.eq(faccount)).list();
            if (list != null && list.size() > 0) {
                return list.get(0).getFdevicesMac();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String queryDeviceBeanNameByType(String type, String faccount) {
        try {
            DeviceBeanDao sqlDao = AppApplication.getDaoInstant().getDeviceBeanDao();
            List<DeviceBean> list = sqlDao.queryBuilder().where(DeviceBeanDao.Properties.FdeviceType.eq(type),
                    DeviceBeanDao.Properties.Faccount.eq(faccount)).list();
            if (list != null && list.size() > 0) {
                return list.get(0).getFdevicesName();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //----------------------垃圾记录相关---------------------------------------------
    /**
     * 插入垃圾
     *
     * @param bean
     * @return
     */
    public static long insertPrintDataBean(PrintDataBean bean) {
        PrintDataBeanDao sqlDao = AppApplication.getDaoInstant().getPrintDataBeanDao();
        return sqlDao.insertOrReplace(bean);
    }

    /**
     * 删除
     *
     * @param bean
     * @return
     */
    public static void deletePrintDataBean(PrintDataBean bean) {
        PrintDataBeanDao sqlDao = AppApplication.getDaoInstant().getPrintDataBeanDao();
        sqlDao.delete(bean);
//        sqlDao.queryBuilder().where(RecycleWeighBeanDao.Properties.WeightId.eq(bean.getWeightId())).buildDelete().executeDeleteWithoutDetachingEntities();
    }

    /**
     * 更新
     *
     * @param bean
     * @return
     */
    public static void updatePrintDataBean(PrintDataBean bean) {
        PrintDataBeanDao sqlDao = AppApplication.getDaoInstant().getPrintDataBeanDao();
        sqlDao.update(bean);
//        sqlDao.queryBuilder().where(RecycleWeighBeanDao.Properties.WeightId.eq(bean.getWeightId())).buildDelete().executeDeleteWithoutDetachingEntities();
    }

    /**
     * 查询垃圾记录
     * @param equipmentNo
     * @return
     */
    public static List<PrintDataBean> getPrintDataBeanList(String equipmentNo, String fst) {
        if (TextUtils.isEmpty(equipmentNo)) {
            return null;
        }
        try {
            PrintDataBeanDao sqlDao = AppApplication.getDaoInstant().getPrintDataBeanDao();
            List<PrintDataBean> list;
            if (StringUtils.isTrimEmpty(fst)) {
                list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo))
                        .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
            } else {
                list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo),
                        PrintDataBeanDao.Properties.Fst.eq(fst))
                        .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
            }
            if (list != null && list.size() > 0) {
                return list;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<PrintDataBean> getPrintDataBeanListByCondition(String equipmentNo, String beginDate, String endDate, String type) {
        if (TextUtils.isEmpty(equipmentNo)) {
            return null;
        }
        try {
            PrintDataBeanDao sqlDao = AppApplication.getDaoInstant().getPrintDataBeanDao();
            List<PrintDataBean> list;
            if (StringUtils.isTrimEmpty(type)) {
                if (!StringUtils.isTrimEmpty(beginDate) && !StringUtils.isTrimEmpty(endDate)) {
                    list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo),
                             PrintDataBeanDao.Properties.Fcdate.between(beginDate, endDate))
                            .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
                } else if(!StringUtils.isTrimEmpty(beginDate)) {
                    list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo),
                            PrintDataBeanDao.Properties.Fcdate.ge(beginDate))
                            .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
                } else if(!StringUtils.isTrimEmpty(endDate)) {
                    list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo),
                            PrintDataBeanDao.Properties.Fcdate.le(endDate))
                            .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
                } else {
                    list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo))
                            .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
                }
            } else {
                if (!StringUtils.isTrimEmpty(beginDate) && !StringUtils.isTrimEmpty(endDate)) {
                    list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo),
                            PrintDataBeanDao.Properties.ProductName.eq(type),
                            PrintDataBeanDao.Properties.Fcdate.between(beginDate, endDate))
                            .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
                } else if(!StringUtils.isTrimEmpty(beginDate)) {
                    list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo),
                            PrintDataBeanDao.Properties.ProductName.eq(type),
                            PrintDataBeanDao.Properties.Fcdate.ge(beginDate))
                            .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
                } else if(!StringUtils.isTrimEmpty(endDate)) {
                    list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo),
                            PrintDataBeanDao.Properties.ProductName.eq(type),
                            PrintDataBeanDao.Properties.Fcdate.le(endDate))
                            .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
                } else {
                    list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo),
                            PrintDataBeanDao.Properties.ProductName.eq(type))
                            .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
                }
            }
            if (list != null && list.size() > 0) {
                return list;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> getPrintDataProducts(String equipmentNo) {
        String queryString =
                "SELECT DISTINCT PRODUCT_NAME FROM " + PrintDataBeanDao.TABLENAME
                        + " ORDER BY FCDATE DESC ";
        ArrayList<String> result = new ArrayList<>();
        Cursor c = AppApplication.getDaoInstant().getDatabase().rawQuery(queryString,new String[]{});
        try {
            if (c != null) {
                if (c.moveToFirst()) {
                    do {
                        result.add(c.getString(0));
                    } while (c.moveToNext());
                }
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return result;
    }

    /**
     * 更新垃圾状态
     * @param equipmentNo
     * @param fst_old
     * @param fst_new
     * @return
     */
    public static long updateCollectTrashFst(String equipmentNo, String fst_old, String fst_new){
        try {
            PrintDataBeanDao sqlDao = AppApplication.getDaoInstant().getPrintDataBeanDao();
            List<PrintDataBean> list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo),
                    PrintDataBeanDao.Properties.Fst.eq(fst_old))
                    .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
            if (list != null && list.size() > 0) {
                for(PrintDataBean obj : list){
                    obj.setFst(fst_new);
                    sqlDao.update(obj);
                }
            }
            return 1;
        } catch (Exception e) {
            e.getStackTrace();
        }
        return -1;
    }

    public static List<String> queryPrintDataBeanBatchCodes(String userId) {
        PrintDataBeanDao sqlDao = AppApplication.getDaoInstant().getPrintDataBeanDao();
        String queryString = "SELECT DISTINCT FCODE FROM " + PrintDataBeanDao.TABLENAME + " where USER_ID =? order by  FCODE_T asc";
        Cursor cursor = sqlDao.getDatabase().rawQuery(queryString, new String[]{userId});
        List<String> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            list.add(cursor.getString(0));
        }
        return list;
    }

    public static PrintDataBean queryPrintDataBeaByPrintCode(String printCode) {
        PrintDataBeanDao sqlDao = AppApplication.getDaoInstant().getPrintDataBeanDao();
        List<PrintDataBean> list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.PrintCode.eq(printCode))
                .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 查询今天最新的打印合计数据
     * @param equipmentNo
     * @param fdate
     * @return
     */
    public static PrintDataBean queryPrintDataBeanTodayLatest(String equipmentNo, String fdate) {
        PrintDataBeanDao sqlDao = AppApplication.getDaoInstant().getPrintDataBeanDao();
        List<PrintDataBean> list = sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo),
                PrintDataBeanDao.Properties.FcodeT.ge(fdate))
                .orderDesc(PrintDataBeanDao.Properties.Fcdate).list();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 删除某个日期之前的数据
     * @param equipmentNo
     * @param fdate
     */
    public static void deletePrintDataBeans(String equipmentNo, String fdate) {
        if (StringUtils.isTrimEmpty(equipmentNo)) {
            return;
        }
        PrintDataBeanDao sqlDao = AppApplication.getDaoInstant().getPrintDataBeanDao();
        sqlDao.queryBuilder().where(PrintDataBeanDao.Properties.EquipmentNo.eq(equipmentNo),
                PrintDataBeanDao.Properties.FcodeT.lt(fdate)).buildDelete().executeDeleteWithoutDetachingEntities();
    }

    //---垃圾类型---------------------------------------------------
    /**
     * 保存我的设备
     *
     * @param bean
     * @return
     */
    public static long insertOrReplaceProductInfoBean(ProductBean bean) {
        ProductBeanDao sqlDao = AppApplication.getDaoInstant().getProductBeanDao();
        return sqlDao.insertOrReplace(bean);
    }

    public static List<ProductBean> queryProductInfoBeans(){
        ProductBeanDao sqlDao = AppApplication.getDaoInstant().getProductBeanDao();
        return sqlDao.queryBuilder().orderAsc(ProductBeanDao.Properties.OrderNum).list();
    }

    ///根据关键字查询产品
    public static List<ProductBean> queryProductInfoBeansByKey(String key){
        ProductBeanDao sqlDao = AppApplication.getDaoInstant().getProductBeanDao();
        if (StringUtils.isTrimEmpty(key)){
            return sqlDao.queryBuilder().orderAsc(ProductBeanDao.Properties.OrderNum).list();
        }
        return sqlDao.queryBuilder().where(ProductBeanDao.Properties.ProductName.like("%"+key+"%")).orderAsc(ProductBeanDao.Properties.ProductId).list();
    }

    //根据id查询产品
    public static ProductBean queryProductInfoBeanById(String id){
        ProductBeanDao sqlDao = AppApplication.getDaoInstant().getProductBeanDao();
        List<ProductBean> list = sqlDao.queryBuilder().where(ProductBeanDao.Properties.ProductId.eq(id)).list();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public static void deleteProductBeans() {
       ProductBeanDao sqlDao = AppApplication.getDaoInstant().getProductBeanDao();
        sqlDao.queryBuilder().buildDelete().executeDeleteWithoutDetachingEntities();
    }

    //---包粽工---------------------------------------------------
    public static long insertOrReplaceWorkerBean(WorkerBean bean) {
        WorkerBeanDao sqlDao = AppApplication.getDaoInstant().getWorkerBeanDao();
        return sqlDao.insertOrReplace(bean);
    }

    public static WorkerBean queryProductWorkerBeanByUserName(String userName){
        WorkerBeanDao sqlDao = AppApplication.getDaoInstant().getWorkerBeanDao();
        List<WorkerBean> list = sqlDao.queryBuilder().where(WorkerBeanDao.Properties.UserName.eq(userName)).list();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public static void deleteWorkerBeans() {
        WorkerBeanDao sqlDao = AppApplication.getDaoInstant().getWorkerBeanDao();
        sqlDao.queryBuilder().buildDelete().executeDeleteWithoutDetachingEntities();
    }
    //---北京瑞德----------------------------------------------------------------

    /**
     * 保存公司信息
     * @param bean
     * @return
     */
    public static long insertOrReplacePropInfoBean(PropInfoBean bean) {
        PropInfoBeanDao sqlDao = AppApplication.getDaoInstant().getPropInfoBeanDao();
        return  sqlDao.insertOrReplace(bean);
    }

    public static PropInfoBean queryPropInfoBeanById(String localId){
        PropInfoBeanDao sqlDao = AppApplication.getDaoInstant().getPropInfoBeanDao();
        List<PropInfoBean> list = sqlDao.queryBuilder().where(PropInfoBeanDao.Properties.LocalId.eq(localId)).list();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public static void deletePropInfoBeanById(String localId) {
        PropInfoBeanDao sqlDao = AppApplication.getDaoInstant().getPropInfoBeanDao();
        List<PropInfoBean> list = sqlDao.queryBuilder().where(PropInfoBeanDao.Properties.LocalId.eq(localId)).list();
        if (list != null && list.size() > 0) {
            sqlDao.delete(list.get(0));
        }
    }

    public static void deletePropInfoBean() {
        PropInfoBeanDao sqlDao = AppApplication.getDaoInstant().getPropInfoBeanDao();
        sqlDao.queryBuilder().buildDelete().executeDeleteWithoutDetachingEntities();
    }

    //供应商信息--------------------------------------------------------------------------------------
    /**
     * 保存供应商信息
     * @param bean
     * @return
     */
    public static long insertOrReplaceSupplierBean(SupplierBean bean) {
        SupplierBeanDao sqlDao = AppApplication.getDaoInstant().getSupplierBeanDao();
        return  sqlDao.insertOrReplace(bean);
    }

    public static void deleteSupplierBeanById(Long id) {
        SupplierBeanDao sqlDao = AppApplication.getDaoInstant().getSupplierBeanDao();
        List<SupplierBean> list = sqlDao.queryBuilder().where(SupplierBeanDao.Properties._id.eq(id)).list();
        if (list != null && list.size() > 0) {
            sqlDao.delete(list.get(0));
        }
    }

    public static List<SupplierBean> querySupplierBeans() {
        SupplierBeanDao sqlDao = AppApplication.getDaoInstant().getSupplierBeanDao();
        List<SupplierBean> list = sqlDao.queryBuilder().orderDesc(SupplierBeanDao.Properties.Fcdate).list();
        return list;
    }

    //客户信息--------------------------------------------------------------------------------------
    /**
     * 保存客户信息
     * @param bean
     * @return
     */
    public static long insertOrReplaceCustomerBean(CustomerBean bean) {
        CustomerBeanDao sqlDao = AppApplication.getDaoInstant().getCustomerBeanDao();
        return  sqlDao.insertOrReplace(bean);
    }

    public static void deleteCustomerBeanById(Long id) {
        CustomerBeanDao sqlDao = AppApplication.getDaoInstant().getCustomerBeanDao();
        List<CustomerBean> list = sqlDao.queryBuilder().where(CustomerBeanDao.Properties._id.eq(id)).list();
        if (list != null && list.size() > 0) {
            sqlDao.delete(list.get(0));
        }
    }

    public static List<CustomerBean> queryCustomerBeans() {
        CustomerBeanDao sqlDao = AppApplication.getDaoInstant().getCustomerBeanDao();
        List<CustomerBean> list = sqlDao.queryBuilder().orderDesc(CustomerBeanDao.Properties.Fcdate).list();
        return list;
    }
}
